import axios from "axios";

//定义后端接口地址的前缀
axios.defaults.baseURL = "http://127.0.0.1:80"
//  axios.defaults.baseURL="http://117.72.75.183:8888"

// 添加请求拦截器
axios.interceptors.request.use(
    function (config) {
        // 在发送请求之前做些什么
        const jwtToken = localStorage.getItem('jwtToken');
        if (jwtToken) {
            config.headers.heart = `${jwtToken}`;
        }
        return config;
    },
    function (error) {
        // 对请求错误做些什么
        return Promise.reject(error);
    }
);

// 设置响应拦截器
axios.interceptors.response.use(
    response => {
        // 对响应数据做点什么
        return response;
    },
    error => {
        // 对响应错误做点什么
        if (error.response) {
            // 服务器返回了错误状态码
            if (error.response.status === 401) {
                // 这里可以根据需要修改消息内容
                window.location.href = '/'; // 将用户重定向到登录页面
            }
        }
        return Promise.reject(error);
    }
);

export function doGet(url, params) {
    return axios({
        method: "get",
        url: url,
        params: params, //{name:"",age:22},
        headers: {
            'Content-Type': 'application/json;charset=utf-8', // 设置正确的 Content-Type
            'Authorization': 'b8b6',
            'MzheartQ': localStorage.getItem('jwtToken'),
        }
    })
}

export function doDelete(url, params) {
    return axios({
        method: "delete",
        url: url,
        params: params, //{name:"",age:22},
        dataType: "json"
    })
}

export function doPost(url, data) {
    return axios({
        method: "post",
        url: url,
        data: data, //{name:"",age:22},
        headers: {
            'Content-Type': 'application/json;charset=utf-8', // 设置正确的 Content-Type
            'Authorization': 'b8b6',
            'MzheartQ': localStorage.getItem('jwtToken'),
        }
    })
}

export function doPut(url, data) {
    return axios({
        method: "put",
        url: url,
        data: data, //{name:"",age:22},
        dataType: "json"
    })
}

